package com.hzjq.core.worker

import com.hzjq.core.BlastDelegate
import com.hzjq.core.ErrorCode
import com.hzjq.core.bean.CapEntity
import com.hzjq.core.bean.CapProgressEntity
import com.hzjq.core.bean.ErrorReadCapEntity
import com.hzjq.core.callback.Callback
import com.hzjq.core.callback.ProgressCallback

class UnderScanShipWork : ScanShipCapWork {

    private var callbackResult: Callback<ErrorReadCapEntity>? = null // 该值不为空时，在做方案的下传

    private var caps: MutableList<CapEntity>? = null

    private var resultCallback: ProgressCallback<CapProgressEntity>? = null

    private var underErrorReadWork:UnderErrorReadWork?=null

    constructor(resultCallback: ProgressCallback<CapProgressEntity>?, callbackResult: Callback<ErrorReadCapEntity>?, callback: Callback<MutableList<CapEntity>>?) : super(callback){
        this.callbackResult = callbackResult
        this.resultCallback = resultCallback
    }

    override fun onDoWorkStart(vararg args: Any) {
        caps = args[1] as MutableList<CapEntity>
        onProgressChanged((30 + progress * (10f / 100)).toInt(), if(pe == null || pe!!.total == 0)"正在检测雷管信息" else "已检测到${pe!!.total}发雷管")
    }

    override fun onScanShipSuccess(progress: CapProgressEntity) {
        resultCallback?.onResult(progress)
        if(pe != null && pe!!.total > BlastDelegate.getDelegate().getMaxSupportCapCount()){
            underErrorReadWork = UnderErrorReadWork(callbackResult)
            underErrorReadWork?.cancel()
            underErrorReadWork?.doWork(progress.total)
        } else {
            if (progress.stateCode == 0) {
                if (progress.progress < 100) {
                    retry(progress.progress, caps!!)
                } else {
                    val e = ErrorReadCapEntity()
                    e.caps.addAll(caps!!)
                    callbackResult?.onResult(e)
                }
            } else {
                if(progress.stateCode == 3){//没有雷管
                    callback?.onError(ErrorCode.getErrorResult(3))
                    onDestroy()
                } else {
                    underErrorReadWork = UnderErrorReadWork(callbackResult)
                    underErrorReadWork?.cancel()
                    underErrorReadWork?.doWork(progress.total)
                    onDestroy()
                }
            }
        }
    }

    override fun cancel() {
        underErrorReadWork?.cancel()
        super.cancel()
    }
}